<?php

namespace app\api\controller\v2;

use addons\third\library\Service;
use addons\third\model\Third;
use app\api\logic\Platform;
use app\common\behavior\JuheSms;
use app\common\controller\Api;
use app\common\library\CreateUser;

use app\common\model\Suggestion;
use app\common\validate\UserValidate;
use fast\Http;


/**
 * 首页接口
 */
class User extends Api
{
    protected $noNeedLogin = ['third'];
    protected $noNeedRight = '*';

    /**
     * 微信小程序登录
     * v2版本
     */
    public function third()
    {
        $configData = get_addon_config('third');
        $config = $configData['wechat'];
        if (!$config) {
            $this->error(__('未配置小程序'));
        }
        $code = $this->request->post("code");
        $rawData = $this->request->post("rawData", '', 'trim');
        $token = $this->request->post('token');
        if (!$code || !$rawData) {
            $this->error("参数不正确");
        }
        $userInfo = (array)json_decode($rawData, true);
        $params = [
            'appid'      => $config['app_id'],
            'secret'     => $config['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                //如果有传Token
                if ($token) {
                    $this->auth->init($token);
                    //检测是否登录
                    if ($this->auth->isLogin()) {
                        $third = Third::where(['openid' => $json['openid'], 'platform' => 'wxapp'])->find();
                        if ($third && $third['user_id'] == $this->auth->id) {
                            $this->success("登录成功", ['userInfo' => $this->userInfo()]);
                        }
                    }
                }

                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => $userInfo['nickName'],
                    ],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
                $ret = Service::connect($platform, $result, $extend,24*2*3600);
                if ($ret) {
                    $this->success("登录成功", ['userInfo' => $this->userInfo()]);
                } else {
                    $this->error("连接失败");
                }
            } else {
                $this->error("登录失败");
            }
        }


        $this->error('链接微信服务器授权失败');
    }

    /**
     * 用户信息
     */
    private function userInfo() {
        $userinfo = CreateUser::instance()->userInfo();

        if (!defined('PLATFORM_KEY')) {
            $this->error('请先平台鉴权');
        }

        $token = Platform::instance()->setKey(PLATFORM_KEY)->encode($userinfo['token']);
        $userinfo['token'] = $token;
        return $userinfo;
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo() {
        $user = $this->userInfo();
        $this->success('用户信息', $user);
    }

    /**
     * 修改会员个人信息  身份认证
     */
    public function certification()
    {
        $user = $this->auth->getUser();
        //已经认证过 不能重复认证
        if ($user->is_renzheng == 1) {
            $this->error('您已认证成功,不能重复认证');
        }
        $identity_card_front = input('identity_card_front');
        $identity_card_back = input('identity_card_back');
        (new UserValidate())->goCheck('certification', ['identity_card_front'=> $identity_card_front, 'identity_card_back'=>$identity_card_back]);
        //进行认证
        $frontData = [
            'img' => $identity_card_front,
            'type' => 'front'
        ];
        $backData = [
            'img' => $identity_card_back,
            'type' => 'back'
        ];
        $front = (new JuheSms())->juheImg($frontData);
        $back = (new JuheSms())->juheImg($backData);

        if ($back['side'] !== 'back') {
            $this->error('背面身份证上传错误');
        }
        if (!$front['idcard']) {
            $this->error('身份证信息有误');
        }
        $user->identity_card_front = $identity_card_front;
        $user->identity_card_back = $identity_card_back;
        $user->real_name = $front['realname'];
        $user->identity_card = $front['idcard'];
        $user->username = $front['idcard'];
        $user = CreateUser::instance()->updateUser($user);

        //更新用户成功重新登陆
        if ($this->auth->direct($user['id'])) {
            $this->success('认证成功', $this->userInfo());
        } else {
            $this->error('重新登陆失败');
        }
    }


    //已经反馈
    public function suggestion() {
        $content = input('content/s', '');
        if($content == '') {
            $this->error('请填写反馈内容');
        }

        Suggestion::create([
            'content'  =>  $content,
            'user_id' =>  UID
        ]);

        $this->success('提交成功');
    }
}
